import {Token}                  from '../utils/Storage';
import {postMethod}             from "../utils/fetch";
import {CALL_API, ACTIVE}       from "../constants";

//获取会员信息
const fetchGet = () => ({
    [CALL_API]: {
        url: `VMembers/selectKkhcodeByMId?m_id=${Token.getUserId()||Token.getMid()}`,
        types: ACTIVE.get.types(),
        extra: r => {
            var {m_id, jifen, boss, crsq, cardid, sexid, kkhname, kkhcode, callnum, head_url} = r.data;
            return Object.assign(r, {
                data: {
                    _id: cardid,
                    id: m_id.toString(),
                    qr: kkhcode,
                    sex: sexid,
                    name: kkhname,
                    phone: callnum,
                    avatar: head_url,
                    isAdmin: boss === '1',
                    birthday: crsq,
                    accumulate: jifen,
                }
            });
        }
    }
});

//激活会员
const fetchAdd = ({sex, name, phone, birthday}) => ({
    [CALL_API]: {
        url: 'VMembers/insertVMember',
        types: ACTIVE.add.types(),
        options: postMethod({
            crsq: birthday,
            wx_id: Token.getAppId(),
            sexid: sex,
            kkhname: name,
            callnum: phone,
            head_url: _.get(Token.getInfo(), 'avatar', ''),
        }),
    }
});

//修改会员
const fetchEdit = ({sex, name, phone, avatar, birthday}) => ({
    [CALL_API]: {
        url: 'VMembers/updateVMemberByMId',
        types: ACTIVE.edit.types(),
        options: postMethod({
            m_id: Token.getUserId(),
            crsq: birthday,
            wx_id: Token.getAppId(),
            sexid: sex,
            kkhname: name,
            callnum: phone,
            head_url: avatar,
        }),
    }
});

//获取验证码
const fetchIdent = phone => ({
    [CALL_API]: {
        url: `VMembers/getMsgVerifyCode?callnum=${phone}`,
        types: ACTIVE.ident.types(),
    }
});

//手机号查重
const fetchDistinct = phone => ({
    [CALL_API]: {
        url: `VMembers/selectCallnumIsOne?callnum=${phone}`,
        types: ACTIVE.distinct.types(),
        hideError: true,
    }
});

export const ident = phone                          => dispatch => dispatch(fetchIdent(phone));
export const userInfo = ()                          => dispatch => dispatch(fetchGet());
export const distinct = phone                       => dispatch => dispatch(fetchDistinct(phone));
export const activeAdd = entity                     => dispatch => dispatch(fetchAdd(entity));
export const activeEdit = entity                    => dispatch => dispatch(fetchEdit(entity));
